/*
 * JaCoLiB
 * Copyright (C) 2008 Alessandro Serra
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */

package it.gashale.jacolib.connection.connector;

import it.gashale.jacolib.connection.Connection;
import it.gashale.jacolib.connection.auth.Authenticator;
import it.gashale.jacolib.core.JacolibError;
import it.gashale.jacolib.core.ProtocolError;

import java.io.IOException;
import java.net.Socket;
import java.net.InetSocketAddress;

public class ClientConnector extends Connector {
	private String host;
	
	public ClientConnector(String host, int port, String secret, ConnectionHandler handler) throws JacolibError {
		super(port,secret,handler);
		this.host=host;
	}
	
	public Connection connect() throws JacolibError {
		Connection con=null;
		Socket socket=new Socket();
		try {
			socket.connect(new InetSocketAddress(host,getPort()));
			boolean hello=Authenticator.authenticate(socket,getSecretString());
			if(hello) {
				con=new Connection(socket);
			} else {
				throw new ProtocolError("authorization failure");
			}
		} catch (IOException e) {
			throw new JacolibError(e.toString());
		}
		return con;
	}
}
